import 'package:flutter/cupertino.dart';
import 'package:client/common/conn.dart';
import 'package:client/common/event.dart';
import 'package:client/common/info_route.dart';
import 'package:client/model/chatroom_member_model.dart';

class ChatroomMemberProvider extends ChangeNotifier {
  List<ChatroomMemberModel> _list = [];
  bool _init = false;

  ChatroomMemberProvider() {
    bus.on(EventBusSet.chatroomOnline, (arg) {
      // print("arg-->");
      // print(arg);
      // print(arg.runtimeType);

      for (var online in _list) {
        if (online.uuid == arg["uuid"]) {
          return;
        }
      }
      var tmp = ChatroomMemberModel();
      tmp.name = arg["name"];
      tmp.uuid = arg["uuid"];
      _list.add(tmp);
      print("oneline");
      print(_list);
      notifyListeners();
    });

    bus.on(EventBusSet.chatroomOffline, (arg) {
      print("offline");
      print(arg);
      var tmp = ChatroomMemberModel();
      tmp.name = arg["name"];
      tmp.uuid = arg["uuid"];
      for (var i = 0; i < _list.length; i++) {
        if (arg["uuid"] == _list[i].uuid) {
          _list.removeAt(i);
        }
      }
      notifyListeners();
    });

    bus.on(EventBusSet.chatroomMember, (arg) {
      List payload = arg;
      setList(payload);
      _init = true;
      notifyListeners();
    });
  }

  init() {
    _list = [];
    _init = false;
  }

  setList(List list) {
    _list = [];
    if (list.isNotEmpty) {
      for (var item in list) {
        var tmp = ChatroomMemberModel();
        tmp.name = item["name"];
        tmp.uuid = item["uuid"];
        _list.add(tmp);
      }
    }
  }

  List<ChatroomMemberModel> getList() {
    if (_init == false) {
      //初始化
      Conn.send(InfoRoute.reqChatroomMember, "");
    }
    return _list;
  }
}
